package com.powergisol.gis.service.impl;


import com.powergisol.core.modle.VirtualDrillCreater;
import com.powergisol.gis.dto.ModulePoygonDTO;
import com.powergisol.gis.dto.VirtualDrillDTO;
import com.powergisol.gis.geom.GeoPoint;
import com.powergisol.gis.geom.GeoPolygon;
import com.powergisol.gis.service.VirtualDrillService;
import com.powergisol.gis.support.ModuleResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class VirtualDrillServiceImpl implements VirtualDrillService {


    @Autowired
    private ModuleResolver moduleResolver;


//    public void setModuleResolver(ModuleResolver moduleResolver) {
//        this.moduleResolver = moduleResolver;
//    }

    @Override
    public List<VirtualDrillDTO> getIntersection(@NotNull GeoPoint point, @NotNull String plane) throws IOException {


        VirtualDrillCreater virtualDrillCreater = new VirtualDrillCreater();
        /**
         * 我们分几步运算，先将面和点投影，如果点在面里面，那么点和面才能相交，排除经过点的直线和面相交的位置不在三个顶点之内
         */

        List<ModulePoygonDTO> listPolygon = moduleResolver.getListPolygon(plane);
        /**
         * 存储包含点的面
         */
        List<VirtualDrillDTO> intersect = new ArrayList<>();
        listPolygon.forEach(dto -> {
            GeoPolygon polygon = dto.getGeoPolygon();
            if(contains(polygon,point)){

                GeoPoint intersectPoint = virtualDrillCreater.getIntersectPointByMath(polygon, point);
                VirtualDrillDTO drillDTO = new VirtualDrillDTO(dto.getLevel(),intersectPoint);
                intersect.add(drillDTO);
            }

        });

        if(intersect.isEmpty()){
            throw new RuntimeException("所选的点经过的垂直线与模型无交点");
        }

        return intersect;

    }

    /**
     * 判断面里面是否包含某个点,包括点在面边上的情况
     * @param polygon
     * @param point
     * @return
     */
    private boolean contains(GeoPolygon polygon,GeoPoint point){
        return polygon.toGeometry().intersects(point.toGeometry());
    }


}
